package com.itcam.phaseiii.listener_;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * Author:Cammy.Wu
 * Date:2024-05-11
 * Description:焦点
 */

public class Tips {
    /**
     * 焦点：程序的注意力集中在某一组件上
     *
     * 注意：按钮组件比较特殊，创建后，默认停留在按钮组件上，实际上它不用占用程序的焦点
     *      通过 btn.setFocusable(flase) 取消焦点
     */
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setLayout(null);

        JButton btn = new JButton("按钮");
        btn.setBounds(0, 0, 100, 100);
        frame.getContentPane().add(btn);

        //--------------------------------------------------------------------------------------------------------------

        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("点击了...");
            }
        });

        // 取消按钮焦点
        btn.setFocusable(false);

        //--------------------------------------------------------------------------------------------------------------

        frame.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) { // 键入某个按键时调用该方法

            }

            @Override
            public void keyPressed(KeyEvent e) { // 按下某个按键时调用该方法
                // 获取键盘的ascII码值
                int keyCode = e.getKeyCode();
                if (keyCode == 37) {
                    System.out.println("←");
                } else if (keyCode == 38) {
                    System.out.println("↑");
                } else if (keyCode == 39) {
                    System.out.println("→");
                } else if (keyCode == 40) {
                    System.out.println("↓");
                }
            }

            @Override
            public void keyReleased(KeyEvent e) { // 释放某个按键时调用该方法

            }
        });

        frame.setVisible(true);
    }
}
